package com.eagle.functioninterface;

import com.eagle.enitity.Student;
import org.junit.Test;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.function.BiPredicate;

/**
 * {@link java.util.function.BiPredicate} 可以看成{@link java.util.function.BiFunction} 接口的
 * 一种特殊形式 r=f(t,u) 当r=boolean时BiFunction就跟BiFunction一样
 *
 * @author qinlinsen
 */
public class BiPredicateTest9 {
    private static final List<Student> studentList = Arrays.asList(
            new Student("洪七公", 28, "丐帮"),
            new Student("黄老邪", 29, "桃花岛"),
            new Student("郭靖", 12, "蒙古"),
            new Student("张三丰", 30, "武当"),
            new Student("灭绝师太", 3, "峨眉山"),
            new Student("安迪", 32, "上海"),
            new Student("樊胜美", 30, "无锡"),
            new Student("彭总", 33, "上海"));

    @Test
    public void testBiPredicate() {
        final boolean result = judge("hello", "h1", (x, y) -> x.startsWith("h") && y.startsWith("h"));
        System.out.println(result);
    }


    @Test
    public void testFilter() {
        //筛选出学生的年龄在30岁以上,并且是上海户口的人
        final List<Student> targetStudentList = filter(studentList, (age, address) -> age > 30 && address.contains("上海"));
        targetStudentList.forEach(System.out::println);
    }


    private <T, U> boolean judge(T x, U y, BiPredicate<T, U> condition) {
        final boolean result = condition.test(x, y);
        return result;
    }


    private List<Student> filter(List<Student> sourceStudentList, BiPredicate<Integer, String> processor) {
        Objects.requireNonNull(sourceStudentList);
        Objects.requireNonNull(processor);
        final List<Student> targetStudentList = new ArrayList<>();
        for (Student student : sourceStudentList) {
            //筛选中满足一定条件的学生
            if (processor.test(student.getAge(), student.getAddress())) {
                targetStudentList.add(student);
            }
        }
        return targetStudentList;
    }

}
